package com.fzrskj.cloud.free.user.utils.agent;


import com.fzrskj.cloud.free.core.enums.DicParamEnum;
import com.fzrskj.cloud.free.core.enums.ProductTypeEnum;
import com.fzrskj.cloud.free.dic.bean.DicParam;
import com.fzrskj.cloud.free.dic.utils.DicParamUtils;
import com.fzrskj.cloud.free.sys.bean.SysProduct;
import com.fzrskj.cloud.free.sys.bean.User;
import com.fzrskj.cloud.free.sys.dao.SysProductDao;
import com.fzrskj.cloud.free.sys.dao.SysProductPriceDao;
import com.fzrskj.cloud.free.sys.utils.CUserUtils;
import com.fzrskj.cloud.free.sys.utils.SysProductUtils;
import com.fzrskj.cloud.free.user.bean.UserAccountView;
import com.fzrskj.cloud.free.user.utils.UserAccountUtils;
import ms.core.object.CObject;
import ms.core.tool.StrTool;
import org.apache.commons.collections.map.HashedMap;

import java.util.*;

/**
 * UserAgentUtils.
 *
 * @author zj.
 * Created on 2019/8/14 0014.
 */
public class UserAgentUtils extends CObject {
    //导航名称
    final public static String PLATFORMNAVIGATION = "platformNavigation";
    final public static String PLATFORMNAVIGATIONTALOS = "platformNavigationTalos";
    /**
     * 设置代理.
     *
     * @param userId  用户ID.
     * @param isAgent 是否为代理.
     * @return 结果.
     */
    public Boolean modify(Integer userId, String isAgent) {
        //更新用户
        Map<String, Object> updateUser = new HashedMap();
        updateUser.put("isAgent", isAgent);
        Map<String, Object> cdtUser = new HashedMap();
        cdtUser.put("userId", userId);
        UserAccountUtils accountUtils = new UserAccountUtils();
        UserAccountView account = accountUtils.queryUserAccountViewByUid(userId);
        if (null == account) {
            this.setErrCode("USER NOT FOUND", "未找到用户");
            return false;
        }
        if ("Y".equals(isAgent)) {
            if (StrTool.isBlankStr(account.getAgentApiPass())) {
                updateUser.put("agentApiPass", UUID.randomUUID().toString());
            }
            if (StrTool.isBlankStr(account.getApiAccessKey())) {
                updateUser.put("apiAccessKey", UUID.randomUUID().toString());
            }
        }
        accountUtils.modUserAccount(updateUser, cdtUser);

        //设置代理后台账号
        CUserUtils cUserUtils = new CUserUtils();

        Map<String, Object> cdtAdmin = new HashedMap();
        cdtAdmin.put("agentId", userId);

        if ("Y".equals(isAgent)) {
            List<User> userList = cUserUtils.queryUserNoAgent(cdtAdmin);
            if (null == userList || userList.isEmpty()) {
                cUserUtils.copyAdminRight(userId);

                User user = new User();
                user.setAccount(account.getUserName());
                user.setNick(account.getFullName());
                user.setMobile(account.getMobile());
                user.setState(0);
                user.setAgentId(userId);
                user.setPassword(account.getPassWord());
                user.setUtype((short) 0);
                user.setRoles("[{\"id\":\"admin\"}]");
                cUserUtils.newUserNotAgent(user);
            } else {
                Map<String, Object> updateAdmin = new HashedMap();
                updateAdmin.put("state", 0);
                cUserUtils.modifyUserNotAgent(updateAdmin, cdtAdmin);
            }

            //初始化会员等级
            InitDataOfUserLevelHelper.initUserLevel(userId);

            //初始导航
            this.copyNavigation(userId);

            //初始云产品促销
            this.copyPromotion(userId);
            //初始化模板
            this.copyTemplate(userId);
            this.copyAgentInitDic(userId);

            //初始文章数据
            InitDataOfArticleHelper.copyArticle(userId, account.getUserName());

            //初始通知模板
            InitDataOfNoticeTemplateHelper.initTemplate(userId);

            //复制产品表数据
            this.syncDomainProduct(userId);

            //自定义产品
            this.syncDiyProduct(userId);

            //代理关系维维护
            InitDataSyncAgentRelationHelper.syncAgentRelation(userId, account.getAgentId(), true);
        } else {
            Map<String, Object> updateAgent = new HashedMap();
            updateAgent.put("state", 2);
            cUserUtils.modifyUserNotAgent(updateAgent, cdtAdmin);

            //代理关系维维护
            InitDataSyncAgentRelationHelper.syncAgentRelation(userId, account.getAgentId(), false);
        }
        return true;
    }

    /**
     * 虚机产品同步
     *
     * @param agentId 代理ID
     */
    private void syncVHostProduct(String regType, int agentId) {
        syncSysProduct(ProductTypeEnum.V_HOST.getTag(), regType, agentId);
    }

    /**
     * 云产品配置同步到代理下
     *
     * @param regType 产品注册商
     * @param agentId 代理ID
     */
    private void syncCloudProduct(String regType, int agentId) {
        syncSysProduct(ProductTypeEnum.CLOUD.getTag(), regType, agentId);
    }

    /**
     * 域名产品配置同步到代理下
     *
     * @param agentId 代理ID
     */
    public void syncDomainProduct(int agentId) {
        syncSysProduct(ProductTypeEnum.DOMAIN.getTag(), "", agentId);
    }

    public void syncDiyProduct(Integer agentId) {
        SysProductUtils productUtils = new SysProductUtils();
        productUtils.syncAgentProduct(ProductTypeEnum.DIY.getTag(), agentId);
    }

    /**
     * 同步产品
     *
     * @return
     */
    private boolean syncSysProduct(String productClass, String regType, int agentId) {
        SysProductDao spdao = new SysProductDao();

        //获取代理和主站数据
        List<SysProduct> sysProductList = spdao.queryAgengtSysProduct(productClass, regType, 0);
        List<SysProduct> agentProductList = spdao.queryAgengtSysProduct(productClass, regType, agentId);

        //获取重复数据
        List<SysProduct> doubleProductList = getPublicSysProducts(sysProductList, agentProductList);

        //获取差异数据
        List<SysProduct> addProductList = getDifSysProducts(sysProductList, doubleProductList);
        List<SysProduct> delProductList = getDifSysProducts(agentProductList, doubleProductList);

        //执行删除和添加操作
        delSysProduct(delProductList, agentId);
        addSysProduct(addProductList, agentId);

        spdao.dispose();
        return true;
    }

    /**
     * 对比两个都存在的产品
     *
     * @param sysProductList
     * @param agentProductList
     * @return
     */
    private List<SysProduct> getPublicSysProducts(List<SysProduct> sysProductList, List<SysProduct> agentProductList) {
        List<SysProduct> doubleProductList = new ArrayList<>();

        //取出相同产品
        for (SysProduct sysObj : sysProductList) {
            for (SysProduct agentObj : agentProductList) {
                if (sysObj.getProductCode().equals(agentObj.getProductCode())) {
                    doubleProductList.add(sysObj);
                    break;
                }
            }
        }
        return doubleProductList;
    }

    /**
     * 取出差异产品
     *
     * @param morProductList  数据多的
     * @param lessProductList 数据少的
     * @return
     */
    private List<SysProduct> getDifSysProducts(List<SysProduct> morProductList, List<SysProduct> lessProductList) {
        List<SysProduct> difProductList = new ArrayList<>();
        boolean flag = false;
        //取出相同产品
        for (SysProduct mobj : morProductList) {
            flag = false;
            for (SysProduct lobj : lessProductList) {
                if (mobj.getProductCode().equals(lobj.getProductCode())) {
                    flag = true;
                    break;
                }
            }
            if (!flag) {
                difProductList.add(mobj);
            }
        }

        //反向处理
        for (SysProduct mobj : lessProductList) {
            flag = false;
            for (SysProduct lobj : morProductList) {
                if (mobj.getProductCode().equals(lobj.getProductCode())) {
                    flag = true;
                    break;
                }
            }
            if (!flag) {
                difProductList.add(mobj);
            }
        }
        return difProductList;
    }

    /**
     * 同步新增代理产品
     *
     * @param addProductList 代理新增的产品列表
     * @param agentId        代理标识
     */
    private void addSysProduct(List<SysProduct> addProductList, int agentId) {
        SysProductDao spdao = new SysProductDao();
        SysProductPriceDao sppdao = new SysProductPriceDao();
        //Map<String, Object> value = new HashMap<>();
        for (SysProduct addObj : addProductList) {
            addObj.setCreateTime(new Date());
            addObj.setAgentId(agentId);
            spdao.addAgentSysProduct(addObj);
//            List<SysProductPrice> spplist = sppdao.queryAgentSysProductPrice(addObj.getProductClass(), addObj.getProductCode(), 0);
//            for (SysProductPrice sppobj : spplist) {
//                sppobj.setId(0);
//                sppobj.setAgentId(agentId);
//                sppdao.addAgentSysProductPrice(sppobj);
//            }
        }
        sppdao.dispose();
        spdao.dispose();
    }

    /**
     * 同步删除代理产品
     *
     * @param delProductList 代理删除的产品列表
     * @param agentId        代理标识
     */
    private void delSysProduct(List<SysProduct> delProductList, int agentId) {
        SysProductDao spdao = new SysProductDao();
        SysProductPriceDao sppdao = new SysProductPriceDao();
        Map<String, Object> cdt = new HashMap<>();
        Map<String, Object> pcdt = new HashMap<>();
        for (SysProduct delObj : delProductList) {
            cdt.clear();
            cdt.put("id", delObj.getId());
            cdt.put("agentId", agentId);
            cdt.put("productCode", delObj.getProductCode());
            spdao.delAgentSysProduct(cdt);

            pcdt.clear();
            pcdt.put("agentId", agentId);
            pcdt.put("productCode", delObj.getProductCode());
            pcdt.put("productClass", delObj.getProductClass());
            sppdao.delAgentSysProductPrice(pcdt);
        }
        sppdao.dispose();
        spdao.dispose();
    }

    public static void main(String a[]) {
        List<SysProduct> newProductList = new ArrayList<>();
        List<SysProduct> delProductList = new ArrayList<>();
        System.out.println(System.identityHashCode(newProductList));
        System.out.println(System.identityHashCode(delProductList));
//        newProductList = delProductList.clone();
        System.out.println(System.identityHashCode(newProductList));
        System.out.println(System.identityHashCode(delProductList));
    }

    /**
     * 为代理复制导航.
     * @param userId 用户ID.
     */
    private void copyNavigation(int userId){
        this.copyDicParam(DicParamEnum.NAVIGATION_KEY.getVal(), userId);
        this.copyDicParam(DicParamEnum.NAVIGATION_KEY_TALOS.getVal(), userId);
    }

    private void copyPromotion(Integer agentId) {
        this.copyDicParam(DicParamEnum.CLOUD_PROMOTION.getVal(), agentId);
    }

    private void copyTemplate(Integer agentId){
        this.copyDicParam(DicParamEnum.DEFAULT_TEMPLATE.getVal(),agentId);
    }

    private void copyAgentInitDic(Integer agentId) {
        this.copyDicParam(DicParamEnum.NAV_BAR_IMG.getVal(), agentId);
        this.copyDicParam(DicParamEnum.COM_ADVANTAGE.getVal(), agentId);
        this.copyDicParam("tel", agentId);
        this.copyDicParam("qq", agentId);
        this.copyDicParam("fax", agentId);
        this.copyDicParam("email", agentId);
        this.copyDicParam("webicp", agentId);
        this.copyDicParam("webicp2", agentId);
        this.copyDicParam("addr", agentId);
        this.copyDicParam("postCode", agentId);
        this.copyDicParam("comname", agentId);
        this.copyDicParam("webname", agentId);
        this.copyDicParam("webtitle", agentId);
        this.copyDicParam("weblogo", agentId);
        this.copyDicParam("wechatlogo", agentId);
        this.copyDicParam("certOfficialSeal", agentId);
        this.copyDicParam("diyDomainCertUrl", agentId);
        this.copyDicParam("introduce", agentId);
        this.copyDicParam("supportCodeLogin", agentId);
        this.copyDicParam("codeLoginWay", agentId);
        this.copyDicParam("platformNavigation", agentId);
    }

    /**
     * 向代理复制字典配置.
     * @param paramName
     * @param agentId
     */
    private void copyDicParam(String paramName, Integer agentId) {
        DicParamUtils paramUtils = new DicParamUtils();
        Map<String, Object> navCdt = new HashedMap();
        navCdt.put("paramName", paramName);
        navCdt.put("agentId", agentId);
        DicParam dicParam = paramUtils.qryDicParams(navCdt);
        if(dicParam == null){
            navCdt.put("agentId",0);
            DicParam paramAgent = paramUtils.qryDicParams(navCdt);
            if(paramAgent == null){
                return;
            }
            Map<String, Object> navVal = new HashedMap();
            navVal.put("paramName",paramAgent.getParamName());
            navVal.put("paramValue",paramAgent.getParamValue());
            navVal.put("paramType",paramAgent.getParamType());
            navVal.put("agentId",agentId);
            int ret = paramUtils.newDicParam(navVal);
        }
    }
}
